package com.mls.guardian.executor.master;

import com.mls.guardian.container.MasterContainer;
import com.mls.guardian.dataobj.ServerProcessInfo;
import com.mls.guardian.protocol.RemoteBody;
import com.mls.guardian.protocol.RemoteCommand;
import com.mls.guardian.protocol.body.ServerProcessInfoBody;
import com.mls.guardian.remoting.executor.RemoteExecutor;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by jl on 15/11/25.
 */
public class ServerProcessInfoExecutor implements RemoteExecutor {
    private static final Logger log = LoggerFactory.getLogger(ServerProcessInfoExecutor.class);
    private MasterContainer container;

    public ServerProcessInfoExecutor(MasterContainer container) {
        this.container = container;
    }


    @Override
    public RemoteBody execute(ChannelHandlerContext ctx, RemoteCommand request) throws Exception {
        ServerProcessInfoBody serverProcessInfoBody = (ServerProcessInfoBody) request.getRemoteBody();
        List<ServerProcessInfo> projectList = new ArrayList<>();
        log.info("id[{}] code[{}] exec ServerProcessInfoExecutor  start",request.getRequestId(),request.getCode());
        ServerProcessInfo master = container.getAppController().getProjectAndStatus(serverProcessInfoBody.getProjectName(),container.getRole());
        log.info("id[{}] code[{}] in ServerProcessInfoExecutor  master getProjectAndStatus finish",request.getRequestId(),request.getCode());
        projectList.add(master);

        Map clients = container.getClientDispatch().getClient();
        List<String> listAddr = new ArrayList<String>();
        Iterator iterator = clients.keySet().iterator();
        while (iterator.hasNext()) {
            listAddr.add((String) iterator.next());
        }

        log.info("id[{}] code[{}] in ServerProcessInfoExecutor  send to client start",request.getRequestId(),request.getCode());
        List<RemoteBody> remoteBodyList = container.getClientDispatch().sendRequestToClients(request, listAddr, -1);
        for (int i = 0; i < remoteBodyList.size(); i++) {
            ServerProcessInfoBody body = (ServerProcessInfoBody) remoteBodyList.get(i);

            if(!body.isSuc()){
                serverProcessInfoBody.setSuc(false);
                serverProcessInfoBody.setErrorContent(body.getErrorContent());
                return serverProcessInfoBody;
            }

            projectList.add(body.getProcessInfoList().get(0));
        }

        log.info("id[{}] code[{}] in ServerProcessInfoExecutor  client exec finish request",request.getRequestId(),request.getCode());
        serverProcessInfoBody.setProcessInfoList(projectList);

        return serverProcessInfoBody;
    }
}
